#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题: 数字的四舍五入
问题: 你想对浮点数执行指定精度的舍入运算。
提示 : 
"""

def recipe1():
    """简单的舍入运算"""
    print(f"{round(1.23, 1) = }")
    print(f"{round(1.27, 1) = }")
    print(f"{round(-1.27, 1) = }")
    print(f"{round(1.25361, 3) = }")

    # 注意：值刚好在两个边界的中间的时候， round 函数返回离它最近的偶数
    print(f"{round(1.5, 0) = }")
    print(f"{round(2.5, 0) = }")

def recipe2():
    """ndigits 参数可以是负数"""
    a = 1627731
    print(f"{a = }")
    print(f"{round(a, -1) = }")
    print(f"{round(a, -2) = }")
    print(f"{round(a, -3) = }")

def recipe3():
    """格式化的时候指定精度"""
    x = 1.23456
    print(f"{x = }")
    print(f"{format(x, '0.2f') = }")
    print(f"{format(x, '0.3f') = }")
    print(f"{'value is {:0.3f}'.format(x) = }")

def recipe4():
    """对于大多数使用到浮点的程序，没有必要也不推荐这样做。 尽管在计算的时候会有一点点小的误差，但是这些小的误差是能被理解与容忍的"""
    a = 2.1
    b = 4.2
    print(f"{a = }")
    print(f"{b = }")
    print(f"{a + b = }")
    print(f"{round(a + b, 2) = }")

def main():
    print('recipe1'.center(20, '*'))
    recipe1() 
    print('recipe2'.center(20, '*'))
    recipe2() 
    print('recipe3'.center(20, '*'))
    recipe3() 
    print('recipe4'.center(20, '*'))
    recipe4()     

if __name__ == '__main__':
    main()     